//
//  ViewController.m
//  推行为
//
//  Created by 伍银荣 on 2021/7/14.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"


@interface ViewController ()
@property (nonatomic, weak) UIView *redView;
@property (nonatomic, weak) UIView *blueView;
@property (nonatomic, strong) UIDynamicAnimator *animator;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    redView.backgroundColor = [UIColor redColor];
    [self.view addSubview:redView];
    self.redView = redView;
    
    UIView *blueView = [[UIView alloc]initWithFrame:CGRectMake(150, self.view.bounds.size.height - 50, 50, 50)];
    blueView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:blueView];
    self.blueView = blueView;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self dynamicItem];
}

//动力学元素行为
- (void)dynamicItem {
    //创建动画者对象
    self.animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    //创建行为
    //重力行为
    UIGravityBehavior *gravity = [[UIGravityBehavior alloc]initWithItems:@[self.redView]];
    //碰撞行为
    UICollisionBehavior *collision = [[UICollisionBehavior alloc]initWithItems:@[self.redView, self.blueView]];
    collision.translatesReferenceBoundsIntoBoundary = YES;
    
    //创建动力学元素行为
    UIDynamicItemBehavior *dynamicItem = [[UIDynamicItemBehavior alloc]initWithItems:@[self.blueView]];
    //弹力:默认(0-1)
    dynamicItem.elasticity = 0.5;
    //摩擦力,最小值:0
    dynamicItem.friction = 1;
    //密度:默认值: 1
    dynamicItem.density = 2;
    //阻力:resistance
    dynamicItem.resistance = 10;
    
    //将行为添加到动画者中
    [self.animator addBehavior:gravity];
    [self.animator addBehavior:collision];
    [self.animator addBehavior:dynamicItem];
}


//推行为
- (void)pushWithTouches:(NSSet *)touches {
    UITouch *t = touches.anyObject;
    CGPoint currentPoint = [t locationInView:t.view];
    //创建动画者对象
    self.animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    //创建行为
    //推行为
    //    UIPushBehaviorModeContinuous,  持续推力,速度越来越快
    //    UIPushBehaviorModeInstantaneous  瞬时推力,速度越来越慢
    UIPushBehavior *push = [[UIPushBehavior alloc]initWithItems:@[self.redView] mode:UIPushBehaviorModeInstantaneous];
    //量级,推行为一定要设置量级,量级越大,速度越快
    push.magnitude = 0.5;
    //方向
    // push.angle = M_PI;
    //向量
    CGFloat offsetX = currentPoint.x - self.redView.frame.origin.x;
    CGFloat offsetY = currentPoint.y - self.redView.frame.origin.y;
    push.pushDirection = CGVectorMake(-offsetX, -offsetY);
    //添加行为
    [self.animator addBehavior:push];
}

@end
